package com.yc.bran.snack.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bran.snack.bean.GoodsInfo;
import com.yc.bran.snack.mapper.IGoodsInfoMapper;
import com.yc.bran.snack.service.IGoodsInfoService;

@Service
public class GoodsInfoServiceImpl implements IGoodsInfoService {

	@Autowired
	private IGoodsInfoMapper goodsInfoMapper;

	@Autowired  
	private StringRedisTemplate redisTemplate;
	
    @Value("${web.upload-path}")  
    private String uploadDir; 
    
    private static final String path = "http://127.0.0.1:8888/snackpics/";

	private static final ObjectMapper objectMapper = new ObjectMapper();  

	@Override
	public List<GoodsInfo> selectAllGoodsInfo(int tid) {

		return goodsInfoMapper.selectAllGoodsInfo(tid);
	}

	@Override
	public List<GoodsInfo> getgoodsinfo() {

		return goodsInfoMapper.getgoodsinfo();
	}

	// 从redis里面查询商品数据
	public List<GoodsInfo> getredisGoodsInfo() {  
		String key = "goodsInfoKey";  
		String jsonData = redisTemplate.opsForValue().get(key);  
		List<GoodsInfo> goodsInfoList = null;  

		if (jsonData != null) {  
			try {  
				goodsInfoList = objectMapper.readValue(jsonData, objectMapper.getTypeFactory().constructCollectionType(List.class, GoodsInfo.class));  
			} catch (IOException e) {  
				goodsInfoList = getgoodsinfo();   
			}  
		} else {  
			goodsInfoList = getgoodsinfo();  
			try {  
				String json = objectMapper.writeValueAsString(goodsInfoList);  
				redisTemplate.opsForValue().set(key, json, 3600, TimeUnit.SECONDS);  
			} catch (IOException e) {   
			}  
		}  

		return goodsInfoList;  
	}    

	@Override
	public List<GoodsInfo> selectGoodsInfo(int gid) {

		return goodsInfoMapper.selectGoodsInfo(gid);
	}

	@Override
	public int close(int gid) {
		return goodsInfoMapper.close(gid);
	}

	@Override
	public int open(int gid) {
		return goodsInfoMapper.open(gid);
	}

	@Override
	public List<GoodsInfo> getgoods() {
		return goodsInfoMapper.getgoods();
	}

	@Override
	public int selectGblance(int gid) {
		return goodsInfoMapper.selectGblance(gid);
	}

	@Override
	public int updateGblance(int gid, int newGblance) {
		// TODO Auto-generated method stub
		return goodsInfoMapper.updateGblance(gid, newGblance);
	}

	@Override
	public List<Map<String, Object>> selectbackgoodsinfo() {
		return goodsInfoMapper.selectbackgoodsinfo();
	}

	public List<String> handleFileUpload(List<MultipartFile> files) {  
	    List<String> fileUrls = new ArrayList<>();  
	
	    for (MultipartFile file : files) {  
	        if (!file.isEmpty()) {  
	            try {  
	                // 获取原始文件名  
	            	String uuidFilename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
	                
	                // 构建文件在服务器上的完整保存路径  
	                Path targetLocation = Paths.get(uploadDir).resolve(uuidFilename).normalize();
	                  
	                // 将文件内容复制到服务器上  
	                Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);  
	                  
	                // 构建文件的访问URL  
	                String fileUrl = path + uuidFilename;
	                  
	                // 将URL添加到列表中  
	                fileUrls.add(fileUrl);
	                System.out.println(fileUrls);
	            } catch (IOException ex) {  
	                // 简单的日志记录或错误处理  
	                System.err.println("Error saving file " + file.getOriginalFilename() + ": " + ex.getMessage());  
	                // 这里可以根据需要抛出异常或进行其他处理  
	            }  
	        }  
	    }  
	      
	    return fileUrls;
	}

	@Override
	public int add(Integer tid, String gname, Double gprice, String ginfo, Double gweight, Integer gblance,
			String gpic) {
		return goodsInfoMapper.add(tid, gname, gprice, ginfo, gweight, gblance, gpic);
	}  
}
